using AutoMapper;
using B.S.XZYData.Api.Read.Application.Command.Plan;
using B.S.XZYData.Api.Read.Dto.Plan;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.Plan
{
    /// <summary>
    /// 获取生产计划分页列表处理器
    /// </summary>
    public class GetPlanPageHandler : IRequestHandler<GetPlanPageCommand, ApiPageing<PlanDto>>
    {
        private readonly IBaseRepository<PlanModel> _planRepo;
        private readonly IBaseRepository<PlanItemModel> _planItemRepo;
        private readonly IMapper _mapper;

        public GetPlanPageHandler(
            IBaseRepository<PlanModel> planRepo,
            IBaseRepository<PlanItemModel> planItemRepo,
            IMapper mapper)
        {
            _planRepo = planRepo;
            _planItemRepo = planItemRepo;
            _mapper = mapper;
        }

        public async Task<ApiPageing<PlanDto>> Handle(GetPlanPageCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiPageing<PlanDto>();

            try
            {
                // 构建查询条件
                var query = _planRepo.GetAll();

                // 计划单号模糊查询
                if (!string.IsNullOrWhiteSpace(request.PlanCode))
                {
                    query = query.Where(x => x.Code.Contains(request.PlanCode));
                }

                // 备注模糊查询
                if (!string.IsNullOrWhiteSpace(request.Remark))
                {
                    query = query.Where(x => x.Remark != null && x.Remark.Contains(request.Remark));
                }

                // 创建人查询
                if (!string.IsNullOrWhiteSpace(request.CreateBy))
                {
                    query = query.Where(x => x.CreateBy != null && x.CreateBy.Contains(request.CreateBy));
                }

                // 排序（按创建时间倒序）
                query = query.OrderByDescending(x => x.CreateTime);

                // 获取总数
                var totalCount = query.Count();

                // 分页
                var plans = query
                    .Skip((request.Index - 1) * request.Size)
                    .Take(request.Size)
                    .ToList();

                // 映射到DTO
                var planDtos = _mapper.Map<List<PlanDto>>(plans);

                // 统计每个计划的明细数量
                foreach (var planDto in planDtos)
                {
                    planDto.ItemCount = _planItemRepo.GetAll()
                        .Where(x => x.PlanId == planDto.Id)
                        .Count();
                }

                res.PageData = planDtos;
                res.TotaCount = totalCount;
                res.TotaPage = (int)Math.Ceiling((double)totalCount / request.Size);
                res.Code = ApiEnum.Success;
                res.Msg = "获取生产计划列表成功";
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"获取生产计划列表失败：{ex.Message}";
            }

            return res;
        }
    }
} 